﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using HZ.Supervise.IBLL;
using HZ.Supervise.Model;
namespace HZ.Supervise.Web.Secondphase.ReportHospital
{
    public partial class hospitalAmountSubsidy : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ViewState["query"] = URLUtil.GetSuperviseQueryFromURL(Request);
                //this.btnQuery.AccessKey = "Esc";
               
                BindArea();
                banding();
            }
        }
        //绑定未补助的医院
        private void banding()
        {
            int totalrecord = 0;
            HZ.Supervise.IBLL.IBLL_Prescription iPrescription = HZ.Supervise.BLLFactory.IBl_Prescription();
            string strwhere = " and PSbsidyAmount<PSubsidiesAmount and POrderStatus =1 ";
            string strArea = ddlCity.SelectedValue;
            if (strArea.Equals(""))//如果选全部
            {
                if (CurrentAccount.GetUser().Org.Area.AreaID.Substring(4, 2).Equals("00")) //如果是市级单位可以查看该市下属地方
                {
                    strwhere += " and PAreaId like '" + CurrentAccount.GetUser().Org.Area.AreaID.Substring(0, 4) + "%'";
                }
                else
                {
                   
                        strwhere += " and PAreaId = '" + CurrentAccount.GetUser().Org.Area.AreaID + "'";
                 
                }
            }
            else
            {
                if (ddlCity.SelectedValue == "530101")
                {
                    strwhere += "and PAreaId like '5301%'";
                }
                else
                {
                    strwhere += " and PAreaId = '" + strArea + "'";
                }
            }
            if (!txtHospitalname.Text.Trim().Equals(""))//医院名称
            {
                strwhere += " and PHospitalName  like '%" + txtHospitalname.Text.Trim() + "%'";
            }
            if (!txtStratTime.Text.Trim().Equals("")) //开始时间
            { strwhere += " and PSubmitTime >='" + (new HZ.Common.ConvertHelper(txtStratTime.Text.Trim()).ToDateTime).Value.ToString() + "'"; }
            if (!txtEndTime.Text.Trim().Equals("")) //结束时间
            { strwhere += " and PSubmitTime <='" + (new HZ.Common.ConvertHelper(txtEndTime.Text.Trim()).ToDateTime).Value.ToString() + "'"; }
            DataTable dt = iPrescription.GetHospitaleNoPrescrip(strwhere, this.AspNetPager1.CurrentPageIndex, this.AspNetPager1.PageSize, out totalrecord);
            AspNetPager1.RecordCount = totalrecord;
            this.gvwDetail.DataSource = dt;
            this.gvwDetail.DataBind();


        }
        public void BindArea()
        {
            IBLL_Area ia = new HZ.Supervise.BLL.BLL_Area();
            IList<Area> lstArea = new List<Area>();
            string userAreaId = CurrentAccount.GetUser().Org.Area.AreaID;
            //判断用户所属地区，如果用户是省级的 则可以列出全部区域
            //if (userAreaId == CurrentAccount.GetCurrentDeployArea().AreaID)
            //{
            int i;
            lstArea = ia.GetSonAreas(userAreaId, 1, 0, out i);
            foreach (Area area in lstArea)
            {
                ListItem ddlitem = new ListItem();
                ddlitem.Text = area.AreaName;
                ddlitem.Value = area.AreaID;
                ddlCity.Items.Add(ddlitem);
            }

            ListItem b = new ListItem();
            b.Text = "全部";
            b.Value = "";
            ddlCity.Items.Insert(0, b);


        }
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
            banding();
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            banding();
        }


        //保存
        protected void btnFinish_Click(object sender, EventArgs e)
        {
            HZ.Supervise.IBLL.IBLL_Prescription iPrescription = HZ.Supervise.BLLFactory.IBl_Prescription();
            Model.Subsidy subsidy = new Subsidy();
            IList<Prescription> prescriptionList = new List<Prescription>();
            bool res = false;
            StringBuilder sb = new StringBuilder();
            string strwhere = "  and PSbsidyAmount<PSubsidiesAmount and POrderStatus=1 ", strstartime = "", strendtime = "";
            string userid = CurrentAccount.GetUser().UserID;
            if (!txtStratTime.Text.Trim().Equals("")) //开始时间
            {
                strwhere += " and PSubmitTime >='" + (new HZ.Common.ConvertHelper(txtStratTime.Text.Trim()).ToDateTime).Value.ToString() + "'";
                if (!string.IsNullOrEmpty(txtStratTime.Text.Trim()))
                {
                    strstartime = txtStratTime.Text.Trim();
                }

            }
            if (!txtEndTime.Text.Trim().Equals("")) //结束时间
            {
                strwhere += " and PSubmitTime <='" + (new HZ.Common.ConvertHelper(txtEndTime.Text.Trim()).ToDateTime).Value.ToString() + "'";
                strendtime = txtEndTime.Text.Trim();
            }
            else
            {
                strendtime = System.DateTime.Now.ToString();//无结束时间就是当前时间
            }

            foreach (GridViewRow gdw in gvwDetail.Rows)
            {
                CheckBox check = (CheckBox)gdw.Cells[0].FindControl("CheckBox1");
                if (check.Checked)
                {
                    string SubsidyID = Guid.NewGuid().ToString();
                    string strPrice = ((TextBox)gdw.FindControl("txtCount")).Text.Trim();//补助
                    string strbz = ((TextBox)gdw.FindControl("txtBZ")).Text.Trim();//备注
                    string strareid = ((Label)gdw.FindControl("PAreaId")).Text.Trim();
                    string strarename = ((Label)gdw.FindControl("PAreaname")).Text.Trim();
                    Label strhospitnameLable = (Label)gdw.FindControl("PHospitalName");
                    string strhospitname = strhospitnameLable.Text;
                   
                    if (string.IsNullOrEmpty(strPrice))
                    {
                        Response.Write("<script>alert('请填写补助金额！')</script>");
                        return;
                    }
                    string strPSubsidiesAmount = ((Label)gdw.FindControl("PSubsidiesAmount")).Text.Trim();

                    string strPSbsidyAmount = ((Label)gdw.FindControl("PSbsidyAmount")).Text.Trim();
                    string strhospitalid = ((Label)gdw.FindControl("PHospitalId")).Text.Trim();
                    string PrescriptionID = ((Label)gdw.FindControl("PrescriptionID")).Text.Trim();
                    string SsumAmount = ((Label)gdw.FindControl("PtotalAmount")).Text.Trim();
                    string title = txtRatio3.Text;
                    if (string.IsNullOrEmpty(title))
                    {
                        title = CurrentAccount.GetUser().UserName + DateTime.Now.ToString("yyyyMMddHHmmss") + "结算单";
                    }
                    string strwhere2 = " and PHospitalName='" + strhospitname + "'";
                    //补助金额
                    decimal price = Convert.ToDecimal(strPrice);
                    //应补助金额
                    decimal PSubsidiesAmount = Convert.ToDecimal(strPSubsidiesAmount);
                    //已补助金额
                    decimal PSbsidyAmount = Convert.ToDecimal(strPSbsidyAmount);
                    //判断补助金额的准确性
                    if ((price + PSbsidyAmount) > PSubsidiesAmount)
                    {
                        Response.Write("<script>alert('补助金额不能大于应补助金额！')</script>");
                        return;
                    }


                    //查询出该医院处方单的应补助金额，已补助金额，处方单Id
                    DataTable dt2 = iPrescription.GetHospitaleTB_Prescription(strwhere2 + strwhere);
                    if (dt2.Rows.Count > 0)
                    {
                        if (string.IsNullOrEmpty(strstartime))
                        {
                            strstartime = dt2.Rows[0]["PSubmitTime"].ToString();
                        }
                        //id
                        subsidy.SubsidyID = SubsidyID;
                        //地区Id
                        subsidy.Sareaid =Convert.ToInt32(strareid);
                        //地区名称
                        subsidy.Sareaname = strarename;
                        //医院Id
                        subsidy.SHospitalID = strhospitalid;
                        //医院名称
                        subsidy.SHospitalName = strhospitname;
                        //总金额
                        subsidy.SsumAmount =Convert.ToDecimal(SsumAmount);
                        //已补贴总金额
                        subsidy.SubsidyAmount =Convert.ToDecimal(strPrice);
                        //补贴添加时间
                        subsidy.Saddtime = DateTime.Now;
                        //补贴人
                        subsidy.Sadduserid = userid;
                        //处方单开始时间
                        subsidy.SubsidyStartTime =Convert.ToDateTime(strstartime);
                        //处方单结束时间
                        subsidy.SubsidyEndTime = Convert.ToDateTime(strendtime);
                        //备注信息
                        subsidy.Remark = strbz;
                        //状态
                        subsidy.State = 0;
                        //结算单名称
                        subsidy.SubsidyName = title;
                        //应补贴金额
                        subsidy.Amount = Convert.ToDecimal(strPSubsidiesAmount);
                        for (int i = 0; i < dt2.Rows.Count; i++)
                        {
                            Prescription prescription = new Prescription();
                            //处方单中应补助金额
                            decimal prePSubsidiesAmount = Convert.ToDecimal(dt2.Rows[i]["PSubsidiesAmount"].ToString());
                            //处方单中的已补助金额
                            decimal prePSbsidyAmount = Convert.ToDecimal(dt2.Rows[i]["PSbsidyAmount"].ToString());
                            //判断处方单中是否有已补助金额
                            if (prePSbsidyAmount > 0)
                            {
                                //算出未补贴金额
                                decimal UnPSbsidyAmount = prePSubsidiesAmount - prePSbsidyAmount;
                                //若未补助金额大于补贴金额
                                if (UnPSbsidyAmount > price)
                                {
                                    prescription.POrderStatus = 2;
                                //当前补贴金额 小于未补助金额时，用未补贴金额减去用户所填金额，加上已补贴金额
                                    prescription.PSbsidyAmount = prePSbsidyAmount + (UnPSbsidyAmount - price);
                                    prescription.PSubmitTime = DateTime.Now;
                                    prescription.PSubsidyUserid = userid;
                                    prescription.PrescriptionId = dt2.Rows[i]["PrescriptionId"].ToString();
                                    prescriptionList.Add(prescription);
                                    price = 0;
                                    break;
                                }
                                else
                                {
                                    prescription.POrderStatus = 2;
                                    //当前补贴金额 小于未补助金额时，用未补贴金额减去用户所填金额，加上已补贴金额
                                    prescription.PSbsidyAmount = prePSubsidiesAmount;
                                    prescription.PSubmitTime = DateTime.Now;
                                    prescription.PSubsidyUserid = userid;
                                    prescription.PrescriptionId = dt2.Rows[i]["PrescriptionId"].ToString();
                                    prescriptionList.Add(prescription);
                                    //更新处方单表并把处方单中
                                    price = price - UnPSbsidyAmount;
                                }

                            }

                        }
                        if (price > 0)
                        {
                            for (int j = 0; j < dt2.Rows.Count; j++)
                            {
                                Prescription prescription = new Prescription();
                                //处方单中应补助金额
                                decimal prePSubsidiesAmount = Convert.ToDecimal(dt2.Rows[j]["PSubsidiesAmount"].ToString());
                                //处方单中的已补助金额
                                decimal prePSbsidyAmount = Convert.ToDecimal(dt2.Rows[j]["PSbsidyAmount"].ToString());
                                //添加以补助金额为0的数据
                                if (prePSbsidyAmount <= 0)
                                {

                                    //处方单应补助金额大于补助金额
                                    if (prePSubsidiesAmount > price)
                                    {
                                        string gu = Guid.NewGuid().ToString();
                                        //更新处方单表
                                        prescription.POrderStatus = 2;
                                        //当前补贴金额 小于未补助金额时，用未补贴金额减去用户所填金额，加上已补贴金额
                                        prescription.PSbsidyAmount = prePSbsidyAmount + price;
                                        prescription.PSubmitTime = DateTime.Now;
                                        prescription.PSubsidyUserid = userid;
                                        prescription.PrescriptionId = dt2.Rows[j]["PrescriptionId"].ToString();
                                        prescriptionList.Add(prescription);
                                        price = 0;
                                        break;
                                    }
                                    else
                                    {
                                        prescription.POrderStatus = 2;
                                        //当前补贴金额 小于未补助金额时，用未补贴金额减去用户所填金额，加上已补贴金额
                                        prescription.PSbsidyAmount = prePSubsidiesAmount;
                                        prescription.PSubmitTime = DateTime.Now;
                                        prescription.PSubsidyUserid = userid;
                                        prescription.PrescriptionId = dt2.Rows[j]["PrescriptionId"].ToString();
                                        prescriptionList.Add(prescription);
                                        price = price - prePSubsidiesAmount;
                                    }
                                }
                            }
                        }
                    }
                    res = true;
                }
            }
            int nresult = iPrescription.UpdateAll(subsidy,prescriptionList,0);
         
            if (nresult > 0)
            {
                Response.Write("<script>alert('补贴发放成功！')</script>");
            }
            else
            {
                Response.Write("<script>alert('补贴发放失败！')</script>");
            }
            banding();
            if (!res)
            {
                Response.Write("<script>alert('没有要发放的补贴！')</script>");
            }


        }

        /// <summary>
        /// url编码
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string UrlEncode(object obj)
        {
            if (obj!=null )
            {
                return Server.UrlEncode(obj.ToString());
            }
            else
            {
                return "";
            }
          
        }

        protected void gvwDetail_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "SHospitalName")
            {
                
                string sessionid = Guid.NewGuid().ToString();
                SuperviseQuery query = (SuperviseQuery)ViewState["query"];
                try
                {
                    query.SubsidyID = e.CommandArgument.ToString();
                }
                catch { }
                Session[sessionid] = query;
                string url = "hospitalAmountSubsidyDetailUn.aspx";
                string da = string.Format("{0}?sessionid={1}", url, sessionid);
                Response.Redirect(string.Format("{0}?sessionid={1}&{2}", url, sessionid, query.SubsidyID));
            }
        }
    }
}
